package com.tianqu.tms.www.rental.controller;

import java.io.File;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.CopyFile;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.ImageUtils;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.entity.CarImage;
import com.tianqu.tms.entity.RentalContractInfo;
import com.tianqu.tms.entity.RentalLocationInfo;
import com.tianqu.tms.www.rental.viewhelper.RentalContractAddInputViewHelper;


/**
 * 合同添加-添加确认 controller
 * @author mufeiyu
 */
public class RentalContractAddResultController extends TmsController {
	private Logger logger = Logger.getLogger(RentalContractAddResultController.class);
	private String Serial = null;
	private int cId = 0;
	private String sysPath = null;
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		
		TxController controller = TxController.getTxController();
		RentalContractAddInputViewHelper viewHelper = (RentalContractAddInputViewHelper) uc
				.getAttribute(TmsConstants.VIEWHELP);

		// 添加事务提交异常捕获
		try {
			controller.begin();
			sysPath = (String) uc.getAttribute("sysPath");			
			Serial = viewHelper.getSerial();
			RentalContractInfo contractInfo = RentalContractInfo.getInstance();
			contractInfo = getContractInfo(viewHelper);
			TmsUserProfile profile = uc.getUserProfile();			
			String updataTime = DateUtil.getCurrentTime();
			contractInfo.setInsertUserId(profile.getUniqueId());
			contractInfo.setUpdateUserId(profile.getUniqueId());		
			contractInfo.setInsertTime(Timestamp.valueOf(updataTime));
			contractInfo.setUpdateTime(Timestamp.valueOf(updataTime));		
						
			// 插入市场租赁合同信息表
			contractInfo.insertContractInfo(contractInfo);
			
			// 插入 租赁合同操作记录表
			contractInfo.setHandleType(1);
			contractInfo.insertContractUpdateHistroy(contractInfo);
			
			cId = (int)contractInfo.getId();
			CarImage carImg = CarImage.getInstance();
			/**
			 * 插入图片信息
			 */
			carImg.insertCarImages(getcarInage(viewHelper));		
			controller.commit();
			
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}
	}
	/**
	 * 图片信息
	 * 
	 * @param view
	 * @return
	 */
	private List<CarImage> getcarInage(RentalContractAddInputViewHelper view) {
		List<CarImage> list = new ArrayList<CarImage>();
		if (!StringUtil.isNullOrBlank(view.getPhoto_1())) {
			list.add(carImage(1,view.getPhoto_1()));
			imageUpLoad(view.getPhoto_1(), imagePath(1,view.getPhoto_1()));
		}
		if (!StringUtil.isNullOrBlank(view.getPhoto_2())) {
			list.add(carImage(2,view.getPhoto_2()));
			imageUpLoad(view.getPhoto_2(), imagePath(2,view.getPhoto_2()));
		}
		if (!StringUtil.isNullOrBlank(view.getPhoto_3())) {
			list.add(carImage(3,view.getPhoto_3()));
			imageUpLoad(view.getPhoto_3(), imagePath(3,view.getPhoto_3()));
		}
		if (!StringUtil.isNullOrBlank(view.getPhoto_4())) {
			list.add(carImage(4,view.getPhoto_4()));
			imageUpLoad(view.getPhoto_4(), imagePath(4,view.getPhoto_4()));
		}
		if (!StringUtil.isNullOrBlank(view.getPhoto_5())) {
			list.add(carImage(5,view.getPhoto_5()));
			imageUpLoad(view.getPhoto_5(), imagePath(5,view.getPhoto_5()));
		}
		if (!StringUtil.isNullOrBlank(view.getPhoto_6())) {
			list.add(carImage(6,view.getPhoto_6()));
			imageUpLoad(view.getPhoto_6(), imagePath(6,view.getPhoto_6()));
		}
		if (!StringUtil.isNullOrBlank(view.getPhoto_7())) {
			list.add(carImage(7,view.getPhoto_7()));
			imageUpLoad(view.getPhoto_7(), imagePath(7,view.getPhoto_7()));
		}
		if (!StringUtil.isNullOrBlank(view.getPhoto_8())) {
			list.add(carImage(8,view.getPhoto_8()));
			imageUpLoad(view.getPhoto_8(), imagePath(8,view.getPhoto_8()));
		}
		return list;
	}
	/**
	 * 图片类
	 * 
	 * @param value
	 * @return
	 */
	private CarImage carImage(int key,String imgPath) {
		CarImage carImage = new CarImage();
		carImage.setcId(cId);
		carImage.setImgKey(String.valueOf(key));
		carImage.setImgPath(ImageUtils.getImageUrl( Registry.getConfig(TmsConstants.UPLOAD_RENTAL_IMAGE_PATCH_KEY)+Serial + "/" + imagePath(key,imgPath)));
		carImage.setImgSrc(3);
		carImage.setImgType(String.valueOf(1));
		return carImage;
	}
	/**
	 * 将图片上传到服务器
	 */
	private void imageUpLoad(String Path, String ImageName) {

		sysPath = sysPath.replace("\\tmsweb", "");
		File infoFile = new File(sysPath + Path);
		File outFile = new File(ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOAD_RENTAL_IMAGE_PATCH_KEY) + Serial + "/") + ImageName);
		CopyFile.copy(infoFile, outFile);
	}
	/**
	 * 图片名称
	 * 
	 * @param Key
	 * @return
	 */
	private String imagePath(int Key,String imgPath) {
		String a = "1";
		String k = String.valueOf(Key);
		String t = "3";
		return this.Serial + a + k + t + getImgFormat(imgPath);
	}
	/**
	 * 图片后缀
	 * 
	 * @param imgPath
	 * @return
	 */
	public String getImgFormat(String imgPath) {
		int i = 0;
		if(imgPath.length()==0)return "";
		while (i != -1) {
			// 找到上传文件的类型的位置，这个地方的是'.'
			i = imgPath.indexOf(".");
			/* 截取上传文件的后缀名,此时得到了文件的类型 */
			imgPath = imgPath.substring(i+1).toLowerCase();
		}
		imgPath = "." + imgPath;
		return imgPath;
	}

	/**
	 * 市场租赁合同
	 * 
	 * @param view
	 * @return
	 * @throws ParseException 
	 */
	private RentalContractInfo getContractInfo(RentalContractAddInputViewHelper view) throws ParseException{
		RentalContractInfo contractInfo = new RentalContractInfo();
		//合同信息
		contractInfo.setSerial(view.getSerial());
		contractInfo.setRent(Integer.parseInt(view.getRent().replaceAll(",", "")));
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式 
		contractInfo.setStartDate(new Timestamp(df.parse(view.getStartDate()).getTime()));
		contractInfo.setEndDate(new Timestamp(df.parse(view.getEndDate()).getTime()));
		contractInfo.setLocationSerial(view.getLocationSerial());
		//合同开始的日期
		Date startDate = df.parse(view.getStartDate());
		Date endDate = df.parse(view.getEndDate());
		// 今天的日期
		Date currentDate = df.parse(df.format(new Date(System.currentTimeMillis())));				
		// 比较
		if (startDate.compareTo(currentDate) <= 0 && endDate.compareTo(currentDate) > 0) {
			contractInfo.setStatus(2);
		} else if (endDate.compareTo(currentDate) <= 0) {
			contractInfo.setStatus(3);
		} else if (startDate.compareTo(currentDate) > 0) {
			contractInfo.setStatus(1);
		}
		//合同人信息
		contractInfo.setOwnerName(view.getOwnerName());
		contractInfo.setOwnerIdCardNo(view.getOwnerIdCardNo());
		if(view.getOwnerSex().equals("女"))
		{
			contractInfo.setOwnerSex(2);
		} else {
			contractInfo.setOwnerSex(1);
		}		
		contractInfo.setOwnerBirthday(new Timestamp(df.parse(view.getOwnerBirthday()).getTime()));
		contractInfo.setOwnerPhone(view.getOwnerPhone());
		contractInfo.setOwnerAddress(view.getOwnerAddress());
		contractInfo.setRemark(view.getRemark());
		//图片信息
		contractInfo.setPhoto_1(view.getPhoto_1());
		contractInfo.setPhoto_2(view.getPhoto_2());
		contractInfo.setPhoto_3(view.getPhoto_3());
		contractInfo.setPhoto_4(view.getPhoto_4());
		contractInfo.setPhoto_5(view.getPhoto_5());
		contractInfo.setPhoto_6(view.getPhoto_6());
		contractInfo.setPhoto_7(view.getPhoto_7());
		contractInfo.setPhoto_8(view.getPhoto_8());
		return contractInfo;
	}
}
